package net.lab1024.sa.admin.module.business.core.material.service;

import java.util.List;
import net.lab1024.sa.admin.module.business.core.material.dao.MaterialDao;
import net.lab1024.sa.admin.module.business.core.material.domain.entity.MaterialEntity;
import net.lab1024.sa.admin.module.business.core.material.domain.form.MaterialAddForm;
import net.lab1024.sa.admin.module.business.core.material.domain.form.MaterialQueryForm;
import net.lab1024.sa.admin.module.business.core.material.domain.form.MaterialUpdateForm;
import net.lab1024.sa.admin.module.business.core.material.domain.vo.MaterialVO;
import net.lab1024.sa.admin.util.RedisIdWorker;
import net.lab1024.sa.base.common.util.SmartBeanUtil;
import net.lab1024.sa.base.common.util.SmartPageUtil;
import net.lab1024.sa.base.common.domain.ResponseDTO;
import net.lab1024.sa.base.common.domain.PageResult;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import jakarta.annotation.Resource;

/**
 * 物料信息表 Service
 *
 * @Author ADog
 * @Date 2025-09-19 16:40:32
 * @Copyright 1.0
 */

@Service
public class MaterialService {

    @Resource
    private MaterialDao materialDao;

    @Autowired
    private RedisIdWorker redisIdWorker;
    /**
     * 分页查询
     */
    public PageResult<MaterialVO> queryPage(MaterialQueryForm queryForm) {
        Page<?> page = SmartPageUtil.convert2PageQuery(queryForm);
        List<MaterialVO> list = materialDao.queryPage(page, queryForm);
        return SmartPageUtil.convert2PageResult(page, list);
    }

    /**
     * 添加
     */
    public ResponseDTO<String> add(MaterialAddForm addForm) {
//        使用全局唯一ID暂时代替编码
        long matcode = redisIdWorker.nextId("MATCODE");
        String stringCode = "MATCODE" + matcode;  // 手动添加前缀
        addForm.setMaterialCode(stringCode);
        MaterialEntity materialEntity = SmartBeanUtil.copy(addForm, MaterialEntity.class);
        materialDao.insert(materialEntity);
        return ResponseDTO.ok();
    }

    /**
     * 更新
     *
     */
    public ResponseDTO<String> update(MaterialUpdateForm updateForm) {
        MaterialEntity materialEntity = SmartBeanUtil.copy(updateForm, MaterialEntity.class);
        materialDao.updateById(materialEntity);
        return ResponseDTO.ok();
    }

    /**
     * 批量删除
     */
    public ResponseDTO<String> batchDelete(List<Long> idList) {
        if (CollectionUtils.isEmpty(idList)){
            return ResponseDTO.ok();
        }

        materialDao.deleteBatchIds(idList);
        return ResponseDTO.ok();
    }

    /**
     * 单个删除
     */
    public ResponseDTO<String> delete(Long materialId) {
        if (null == materialId){
            return ResponseDTO.ok();
        }

        materialDao.deleteById(materialId);
        return ResponseDTO.ok();
    }
}
